﻿package birdry.ui	{
	
	
	//	import birdry.ui.RandomMove;
	
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.geom.Point;
	import birdry.ui.RandomMoveEvent;
	
	public class RandomMove extends Sprite	{
		
		private var _canvasWidth:uint;
		private var _canvasHeight:uint;
		private var _speed1:Number;
		private var _speed2:Number;
		private var _probability:Number;
		private var _tempPoint:Point;
		private var _savePoint:Point;
		private var _currentPoint:Point;
		
		public function get speed1(): Number	{
			return _speed1;
		}
		public function set speed1( value: Number ): void	{
			_speed1 = value;
		}
		public function get speed2(): Number	{
			return _speed2;
		}
		public function set speed2( value: Number ): void	{
			_speed2 = value;
		}
		public function get probability (): Number	{
			return _probability ;
		}
		public function set probability ( value: Number ): void	{
			_probability  = value;
		}
		public function get canvasWidth():uint	{
			return _canvasWidth;
		}
		public function set canvasWidth( value: uint ): void	{
			_canvasWidth = value;
		}
		public function get canvasHeight():uint	{
			return canvasHeight;
		}
		public function set canvasHeight( value: uint ): void	{
			_canvasHeight = value;
		}
		
		public function RandomMove( startXY:Point, canvasWidth:uint, canvasHeight:uint, speed:Number=0.01, probability:Number = 0.02): void	{
			_currentPoint = startXY.clone();
			_savePoint = returnRandomPoint();
			_tempPoint = startXY.clone();
			_probability = probability;
			
			_speed1 = speed;
			_speed2 = speed;
			_canvasWidth = canvasWidth;
			_canvasHeight = canvasHeight;
		}
		
		public function start(): void	{
			addEventListener(Event.ENTER_FRAME, onEnterFrame);
		}
		public function stop(): void	{
			removeEventListener(Event.ENTER_FRAME, onEnterFrame);
		}
		
		private function onEnterFrame( e: Event ): void	{
			if (Math.random() < _probability)	{
				_savePoint = returnRandomPoint();
			}
			_tempPoint.x += _speed1 * (_savePoint.x - _tempPoint.x);
			_tempPoint.y += _speed1 * (_savePoint.y - _tempPoint.y);
			
			_currentPoint.x += _speed2 * (_tempPoint.x - _currentPoint.x);
			_currentPoint.y += _speed2 * (_tempPoint.y - _currentPoint.y);
			
			var tempRadian:Number = Math.atan2((_tempPoint.x  - _currentPoint.x), (_tempPoint.y - _currentPoint.y)) + Math.PI;
			var tempAng:Number = tempRadian * -180 / Math.PI;
			
			dispatchEvent( new RandomMoveEvent( _currentPoint.x, _currentPoint.y, tempAng, RandomMoveEvent.RENDER ));
			//_saveX = _currentPoint.x;
			//_saveY = _currentPoint.y;
		}
		
		private function returnRandomPoint(): Point	{
			return new Point( Math.random() * _canvasWidth, Math.random() * _canvasHeight );
		}
		
	}	// class
}	// package